﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Windows.Forms;

namespace Medicalsystem.MCP.FormDesigner.Common
{
    public class CacheManager
    {
        private static CacheManager instance = null;
        private static object locker = new object();
        private Hashtable ObjectCacheStore = new Hashtable();

        private CacheManager()
        {
        }

        public void Add(string key, object storeObject)
        {
            if (!this.ObjectCacheStore.ContainsKey(key))
            {
                this.ObjectCacheStore.Add(key, storeObject);
            }
        }

        public object GetObjFrom(string assemblyName, string objTypeName)
        {
            return Activator.CreateInstance(this.GetType(assemblyName, objTypeName));
        }
        public object GetObjFrom(string assemblyName, string objTypeName, params object[] args)
        {
            return Activator.CreateInstance(this.GetType(assemblyName, objTypeName),args);
        }
       
        public System.Type GetType(string assemblyName, string name)
        {
            return this.Load(assemblyName).GetType(name, true, false);
        }

        public Assembly Load(string assemblyName)
        {
            Assembly assembly = null;
            if (this.ObjectCacheStore.ContainsKey(assemblyName))
            {
                return (Assembly)this.ObjectCacheStore[assemblyName];
            }
            assembly = Assembly.Load(assemblyName);
            this.ObjectCacheStore.Add(assemblyName, assembly);
            return assembly;
        }

        public object Retrieve(string key)
        {
            return this.ObjectCacheStore[key];
        }

        public static CacheManager Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                        {
                            instance = new CacheManager();
                        }
                    }
                }
                return instance;
            }
        }
    }
}
